/*
  Capture sceenshot
*/
Capture = function(db, interval, scale){
 this.interval = interval || 1000 * 60 * 15; // capture interval
 this.toApprove = false; // flag if app has permission to capture
 this.requestedforApproval = false; // flat if app has request to user for approval
 this.scale = scale || 0.7; // scale of images captured
 this.video = document.querySelector('video');
 this.canvas = document.querySelector("#canvas1");
 this.iconURL = chrome.runtime.getURL("/assets/icon_128.png");
 this.db = db;
 
 this.askPermission();
};

Capture.prototype.start = function(taskId){
  this.taskId = taskId;
  var me = this;
  
  me.captureImage();
  this.tickId = setInterval(function(){
    me.captureImage();
  }, this.interval);
};

Capture.prototype.stop = function(){
  clearInterval(this.tickId);
};

/*
  Ask use for permission. It will be invoked once app started
*/
Capture.prototype.askPermission = function(captureImmediately){
  var me = this;
  me.requestedforApproval = true;
  chrome.desktopCapture.chooseDesktopMedia(["screen"], 
    function(streamId){
      if(!streamId){
        me.toApprove = false;
      }else{
        me.toApprove = true;
        navigator.webkitGetUserMedia({
          audio: false,
          video: {
              mandatory: {
                  chromeMediaSource: 'desktop',
                  chromeMediaSourceId: streamId,
                  minWidth: 1280,
                  maxWidth: 1280,
                  minHeight: 720,
                  maxHeight: 720
              }
          }
        }, function(localMediaStream){
          var video = me.video;
          video.src = window.URL.createObjectURL(localMediaStream);
          
          // Event must be added after waiting for a while. It should be a bug of chrome app API
          localMediaStream.onended = function () {
            me.toApprove = false;
            console.log("screenshare end");
          };
          
          if(captureImmediately === true){
            setTimeout(function(){
              me.doCaptureImage();
            }, 200);
          }
        }, function(err) {
          me.toApprove = false;
          console.log("The following error occured: " + err);
        });
      }
      
      me.requestedforApproval = false;
    }
  );
};


/*
  Start to capture. 
  It will check if there is the permission.
  Ask for permission if not.
*/
Capture.prototype.captureImage = function(){
  console.log(this.toApprove + " " + this.requestedforApproval)
  if(this.toApprove === true){
    this.doCaptureImage();
  }else if(this.requestedforApproval === false){
    this.askPermission(true);
  }
};

/*
  Capture screen with scale specified.
*/
Capture.prototype.doCaptureImage = function(){
  this.captureFromVideo(this.canvas, this.scale);
  var dataURL = this.storeImage();
  this.notify(dataURL);
};

Capture.prototype.captureFromVideo = function(canvas, scale){
  var video = this.video;
  canvas.width = video.videoWidth * scale;
  canvas.height = video.videoHeight * scale;
  canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
};



Capture.prototype.storeImage = function(){
  var dataURL = this.canvas.toDataURL("image/jpeg");
  var createdAt = new Date().getTime();
  var rec = {id: createdAt, taskId: this.taskId, createdAt: createdAt, imageData: dataURL};
  this.db.commit(rec);
  return dataURL;
};

Capture.prototype.notify = function(dataURL){
  var options = {
  	type : "image",
  	title: "Capture Notification",
  	message: $('#view').textContent,
  	iconUrl: this.iconURL,
  	imageUrl: dataURL
  };
  chrome.notifications.create("captureNotify", options, function(notifyId){
    setTimeout(function(){
      chrome.notifications.clear(notifyId);
    }, 5000);
  });
};



//Deprecated
Capture.prototype.requestQuota = function(){
  window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024,
    function(grantedBytes){
      console.log('Granted bytes:' + grantedBytes);
    }
  );
};


//Deprecated
Capture.prototype.loadImage = function(){
  var canvas = this.canvas;
  chrome.storage.local.get("img", function(store){
    if(store["img"]){
      var img = new Image();
      img.onload = function(){
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img,0,0);
      };
      img.src = store["img"];
    }
  });  
  
};
